package com.tanhua.server.service;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Voice;
import com.tanhua.domain.mongo.VoiceRemainTime;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.api.mongo.VoiceApi;
import com.tanhua.dubbo.api.mongo.VoiceRemainTimeApi;
import com.tanhua.server.interceptors.UserHolder;
import com.tanhua.vo.VoiceVo;
import org.apache.commons.lang3.RandomUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.bson.types.ObjectId;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Service
public class VoiceService {

    @Reference
    private VoiceApi voiceApi;

    @Reference
    private VoiceRemainTimeApi voiceRemainTimeApi;

    @Reference
    private UserInfoApi userInfoApi;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Autowired
    private FastFileStorageClient fileStorageClient;

    /**
     * 发送语音
     * @param soundFile
     * @return ResponseEntity
     */
    public ResponseEntity sendVoice(MultipartFile soundFile) {
        Long userId = UserHolder.getUserId();
        //今日日期
        String todayTimeStr = new DateTime().toString("yyyy-MM-dd");
        //查询该用户今日已发布语音次数
        int count = voiceApi.findUserById(userId, todayTimeStr);
        if (count == 9) {
            return ResponseEntity.ok(null);
        }
        Voice voice = new Voice();
        String soundFilename = soundFile.getOriginalFilename();
        //获取拓展名
        String suffixName = soundFilename.substring(soundFilename.lastIndexOf(".") + 1);
        StorePath storePath = null;
        try {
            storePath = fileStorageClient.uploadFile(soundFile.getInputStream(), soundFile.getSize(), suffixName, null);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("上传语音失败");
        }
        voice.setSoundUrl(fdfsWebServer.getWebServerUrl() + storePath.getFullPath());
        voice.setUserId(userId);
        //今日发送次数总数减一  PS:暂时忽略此语句,因为前端apk没有接收此参数
        int remainingTimes = 9 - count;
        voice.setRemainingTimes(Integer.valueOf(remainingTimes));
        voiceApi.save(voice);
        return ResponseEntity.ok(null);
    }

    /**
     * 接收语音
     * @return ResponseEntity
     */
    public ResponseEntity getVoice() {

        //获取用户id
        Long userId = UserHolder.getUserId();
        //查询用户今日接收语音是否还有剩余次数
        VoiceRemainTime voiceRemainTime = voiceRemainTimeApi.findVoice(userId);
        VoiceVo vo = new VoiceVo();
        if (voiceRemainTime == null) {
            //查询voice表中所有非本人并且未听过的数据
            List<Voice> voiceList = voiceApi.findVoices(userId,0);
            //获取集合中元素个数
            int size = voiceList.size();
            //从集合中随机抽取一条语音数据
            Voice voice = voiceList.get(RandomUtils.nextInt(0, size));
            UserInfo userInfo = userInfoApi.findById(voice.getUserId());
            BeanUtils.copyProperties(userInfo, vo);

            //把语音状态改为已听过  0:未听  1:已听
            voice.setStatus(1);
            voiceApi.update(voice);
            vo.setSoundUrl(voice.getSoundUrl());
            vo.setRemainingTimes(8);
            //创建用户今日接收语音剩余次数表,放入数据
            voiceRemainTime = new VoiceRemainTime();
            voiceRemainTime.setId(new ObjectId());
            voiceRemainTime.setUserId(userId);
            voiceRemainTime.setRemainingTimes(8);
            voiceRemainTimeApi.save(voiceRemainTime);
        } else {
            Integer times = voiceRemainTime.getRemainingTimes();
            if (times == 0) {
                return null;
            }else {
                int remainTime = --times;
                //查询voice表中所有未被听过的数据
                List<Voice> voiceList = voiceApi.findVoices(userId,0);
                //获取集合中元素个数
                int size = voiceList.size();
                Voice voice = voiceList.get(RandomUtils.nextInt(0, size));
                UserInfo userInfo = userInfoApi.findById(voice.getUserId());
                BeanUtils.copyProperties(userInfo, vo);
                voice.setStatus(1);
                voiceApi.update(voice);
                vo.setSoundUrl(voice.getSoundUrl());
                vo.setRemainingTimes(remainTime);
                //把剩余次数写入voice_time
                voiceRemainTime.setRemainingTimes(remainTime);
                voiceRemainTimeApi.update(voiceRemainTime);
            }

        }
        return ResponseEntity.ok(vo);
    }
}
